<template>
  <div class="text-center" v-if="!props.list || props.list.length === 0">无数据</div>
  <div class="mb-3 bg-hover ps-2 pt-1" @contextmenu="onContextmenu($event, item)"
    v-for="( item, index ) in  props.list " :index="index">
    <el-row @click="uiMethods.openChatWindow(item)">
      <el-col :span="5">
        <el-avatar :src="item?.online ? uiData.defaultAvatar : uiData.defaultAvatar_0" :size="45" />
      </el-col>
      <el-col :span="19" class="w-100">
        <el-row>
          <el-col :span="24" class="fs-7">{{ item.friendName }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="fs-7">{{ item.createTime }}成为好友</el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>

  <AgelContextMenu v-model="contextMenu.show" :x="contextMenu.x" :y="contextMenu.y" :menus="contextMenu.data"
    @select="onSelect" />

  <el-dialog v-model="uiData.centerDialogVisible" title="删除好友" width="300" center>
    <span style="font-size: 1.1em;">
      确定删除&nbsp;
      <span class="text-danger" style="font-size: 1.2em;">
        {{ selectedFriendInfo.friendName }}
      </span>
      &nbsp;吗？
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="deleteFriend()">
          确定
        </el-button>
        <el-button @click="uiData.centerDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, defineEmits } from 'vue';
import { useStore } from '../common/piniaStore';
import { format } from 'timeago.js';
import { Message_File, Message_Groups } from '@renderer/common/type';
import { defaultAvatar, defaultAvatar_0 } from '../common/resource';

const uiData = ref({
  centerDialogVisible: false,
  defaultAvatar: defaultAvatar,
  defaultAvatar_0: defaultAvatar_0
});



const contextMenu = reactive({
  show: false,
  x: 0,
  y: 0,
  data: [
    { title: '删除好友', icon: 'Delete' }
  ]
});

type Friend_Info = {
  friendId: string;
  friendUserName: string;
  friendName: string;
  createTime: string;
  online?: boolean;
}

const store = useStore();

let selectedFriendInfo: Friend_Info;//被选中的好友id

const props = defineProps({
  list: Array<Friend_Info>
});


const emitOpenChatWindow = defineEmits(['open-window', 'apply-chat-status']);

//显示右键菜单
const onContextmenu = (e: MouseEvent, friendInfo: any) => {
  contextMenu.show = false;
  //延迟是为了让动画更加流畅
  setTimeout(() => {
    console.log('已触发右键：', e, friendInfo);
    selectedFriendInfo = friendInfo;
    contextMenu.show = true;
    contextMenu.x = e.clientX;
    contextMenu.y = e.clientY;
    e.preventDefault();
  }, 70);

}

//点击选择菜单功能项
const onSelect = (item: any) => {
  if (item.title === '删除好友') {
    console.log('已触发删除好友');
    uiData.value.centerDialogVisible = true;
  }
}

//删除好友
const deleteFriend = () => {
  store.client?.deleteFriend(
    selectedFriendInfo.friendId,
    selectedFriendInfo.friendName
  );
  uiData.value.centerDialogVisible = false;

  //刷新好友列表
  window.electron.ipcRenderer.send('ipc:refresh-friend-list');
}

const uiMethods = {
  openChatWindow: (userInfo: {
    friendId: string;
    friendUserName: string;
    friendName: string;
    createTime: string;
  }) => {
    //打开私聊窗口
    emitOpenChatWindow('open-window', userInfo);
    //传入好友的id，从本地记录中获取好友的聊天消息记录
    store.client!.getFriendChatMessage(userInfo.friendId).then((res: Message_File) => {
      //获取本地的聊天记录，然后尝试格式化
      const formattedMessage = formatMessages(res);
      //判断格式化后的数据是否为空，为空则表示没有消息记录
      if (formattedMessage.length === 0) {
        window.electron.ipcRenderer.send('ipc:formatted-chat-message', []);
      } else {
        window.electron.ipcRenderer.send('ipc:formatted-chat-message', formattedMessage);
      }
    }).catch((err) => {
      console.log('好友的消息记录有问题：', err);
    });
    //发起私聊
    applyPrivateChat(userInfo);
  }
};

/**
 * 格式化消息记录
 * @param data 消息记录Json消息
 * @returns 格式化后的消息记录组
 */
const formatMessages = (data: Message_File): Message_Groups => {
  //把我的消息和朋友的消息合并为一个数组，然后根据时间戳进行排序
  let combinedMessages = [...data.hisMessage.map(m => ({ ...m, isMine: false, name: data.friendName })),
  ...data.myMessage.map(m => ({ ...m, isMine: true, name: '我' }))]
    .sort((a, b) => a.time - b.time);

  //然后根据时间戳的差值进行分组处理
  let groupedMessages = combinedMessages.reduce((groups: Message_Groups, msg) => {
    let lastGroup = groups[groups.length - 1];
    //如果最后一个分组的时间戳和当前消息的时间戳差值在一个小时之内，则将当前消息添加到该分组中
    if (lastGroup && format(msg.time, 'zh_CN') === format(lastGroup.timeago, 'zh_CN')) {
      lastGroup.messages.push({
        name: msg.name,
        msg: msg.message,
        time: msg.time, //转换为本地时间格式
        isMy: msg.isMine
      });
    } else {
      groups.push({
        timeago: msg.time,
        messages: [{
          name: msg.name,
          msg: msg.message,
          time: msg.time, //转换为本地时间格式
          isMy: msg.isMine
        }]
      });
    }

    return groups;
  }, []);

  return groupedMessages;
};

/**
 * 申请私聊
 * @param userInfo 好友信息
 * @returns Promise<void>
 */
const applyPrivateChat = async (userInfo: {
  friendId: string;
  friendUserName: string;
  friendName: string;
  createTime: string;
}): Promise<void> => {
  //从ipc中发送好友id，查询密钥协商状态
  window.electron.ipcRenderer.send('ipc:check-key-negotiation-user', userInfo.friendId);
  //监听ipc转发的密钥协商结果，如果已完成密钥协商，则状态为true
  window.electron.ipcRenderer.once('ipc:check-key-negotiation-user', async (_, status) => {
    if (status) {
      emitOpenChatWindow('apply-chat-status', true);
    } else {
      const result = await store.client!.applyPrivateChat(userInfo.friendId);
      if (result === true) {
        //密钥协商成功，并将跟我完成协商的好友保存到集合中
        window.electron.ipcRenderer.send('ipc:add-key-negotiation-user', userInfo.friendId);
        emitOpenChatWindow('apply-chat-status', true);
      } else {
        emitOpenChatWindow('apply-chat-status', false);
      }
    }
  })

}
</script>

<style lang="scss" scoped>
.fs-7 {
  font-size: 0.9em;
}

.truncate-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.bg-hover:hover {
  background-color: #e9ecf0;
  cursor: pointer;
}
</style>
